package com.movecar.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.movecar.R;
import com.movecar.dialog.CustomDialog;
import com.movecar.model.CloudBeansBean;
import com.movecar.model.GroupBean;
import com.movecar.model.GroupJoinBean;
import com.movecar.model.OrderInfoBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.ConfigCacheUtil;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 我的订单列表
 * 
 * @author Zhao.JQ
 * 
 */
public class MyorderListActivity extends Activity implements OnClickListener, RequestResultCallback,
		OnItemClickListener {

	private ListView mListView;
	private List<OrderInfoBean> mDataList = new ArrayList<OrderInfoBean>();
	private List<OrderInfoBean> resultList = new ArrayList<OrderInfoBean>();
	private CustomProgressDialog progressDialog = null;
	private DataAdapter dataAdapter;
	private boolean init = false;
	private GroupJoinBean mGroupJoinBean = null;
	private CloudBeansBean mCloudBeansBean = null;

	private ImageLoader imageLoader = null;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_order_list);
		dataAdapter = new DataAdapter(MyorderListActivity.this);
		initView();
	}

	private void initView() {

		// 活动列表
		mListView = (ListView) findViewById(R.id.mListView);
		Button btn_left = (Button) findViewById(R.id.btn_left);

		TextView title = (TextView) findViewById(R.id.title);
		title.setText("我的订单");
		btn_left.setVisibility(View.VISIBLE);
		startProgressDialog();
		btn_left.setOnClickListener(this);

		if (!init) {
			resultList.clear();
			dataAdapter.notifyDataSetChanged();
		}
		jsonData();

		init = false;
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_left:
			finish();
			break;

		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void jsonData() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryOrderNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(MyorderListActivity.this, GroupBean.class, AppConfig.USER).execute(params);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onSuccess(Object object) {

		stopProgressDialog();

		Type type = new TypeToken<List<OrderInfoBean>>() {
		}.getType();
		Gson gson = new Gson();
		String result = (String) object;
		Object fromJson = gson.fromJson(result, type);

		try {
			mDataList = (List<OrderInfoBean>) fromJson;
		} catch (Exception e) {
			return;
		}

		if (mDataList != null) {

			resultList.clear();
			for (OrderInfoBean bean : mDataList) {

				resultList.add(bean);
			}

			dataAdapter = new DataAdapter(MyorderListActivity.this);
			mListView.setAdapter(dataAdapter);
			mListView.setOnItemClickListener(this);

		} else {
			Toast.makeText(getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onFail(String exception) {

		stopProgressDialog();
		dataAdapter = new DataAdapter(MyorderListActivity.this);

		Alert.error(MyorderListActivity.this,"与服务器连接失败，请检查网络");

	}

	class DataAdapter extends BaseAdapter {

		private Activity activity;
		private LayoutInflater inflater;
		private ViewHolder viewHolder = null;

		DataAdapter(Activity activity) {

			this.activity = activity;
			inflater = LayoutInflater.from(activity);
		}

		@Override
		public int getCount() {

			return resultList.size();
		}

		@Override
		public Object getItem(int arg0) {

			return resultList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {

			final ViewHolder viewHolder;

			if (view == null) {
				viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.my_order_list_item, null);
				viewHolder.order_ralative = (RelativeLayout) view.findViewById(R.id.order_ralative);
				viewHolder.order_title = (TextView) view.findViewById(R.id.order_title);
				viewHolder.order_content = (TextView) view.findViewById(R.id.order_content);
				viewHolder.order_code_is_overtime = (TextView) view.findViewById(R.id.order_code_is_overtime);
				viewHolder.order_code_isjoined = (TextView) view.findViewById(R.id.order_code_isjoined);
				viewHolder.order_code_is_valid = (TextView) view.findViewById(R.id.order_code_is_valid);
				viewHolder.red_envelope = (ImageView) view.findViewById(R.id.red_envelope);
				viewHolder.cancel_order = (Button) view.findViewById(R.id.cancel_order);
				viewHolder.order_state = (ImageView) view.findViewById(R.id.order_state);
				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();
			}

			viewHolder.red_envelope.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					Intent intent = new Intent(MyorderListActivity.this, AddMyRedEnvelopesShareActivity.class);
					intent.putExtra("MessageId", resultList.get(position).getRbMsgId());
					intent.putExtra("shareFlag", 0);
					startActivity(intent);

				}
			});
			// 字体加粗
			TextPaint tp = viewHolder.order_title.getPaint();
			tp.setFakeBoldText(true);
			viewHolder.order_title.setText(resultList.get(position).getTitle());

			viewHolder.order_content.setText(resultList.get(position).getOrderContent());

			viewHolder.cancel_order.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startProgressDialog();
					checkSignOut(resultList.get(position).getMessageId());

				}
			});

			if ("0".equals(resultList.get(position).getRbMsgId())) {

				viewHolder.red_envelope.setVisibility(View.GONE);
			} else {

				viewHolder.red_envelope.setVisibility(View.VISIBLE);
			}
			if ("2".equals(resultList.get(position).getFlag())) {
				// order_state_flg.setBackgroundResource(R.drawable.orderf3);
				viewHolder.order_state.setImageResource(R.drawable.is_overtime);
				viewHolder.order_code_is_overtime.setText("No." + resultList.get(position).getCode());
				viewHolder.order_code_is_overtime.setVisibility(View.VISIBLE);

				if ("0".equals(resultList.get(position).getType())) {
					viewHolder.cancel_order.setVisibility(View.GONE);

				} else {
					viewHolder.cancel_order.setVisibility(View.GONE);
				}

				viewHolder.order_code_isjoined.setVisibility(View.GONE);
				viewHolder.order_code_is_valid.setVisibility(View.GONE);
			} else if ("1".equals(resultList.get(position).getFlag())) {
				// order_state_flg.setBackgroundResource(R.drawable.orderf1);
				viewHolder.order_state.setImageResource(R.drawable.is_joined);
				viewHolder.order_code_isjoined.setText("No." + resultList.get(position).getCode());
				viewHolder.order_code_isjoined.setVisibility(View.VISIBLE);

				if ("0".equals(resultList.get(position).getType())) {
					viewHolder.cancel_order.setVisibility(View.GONE);

				} else {
					viewHolder.cancel_order.setVisibility(View.GONE);
				}
				viewHolder.order_code_is_overtime.setVisibility(View.GONE);
				viewHolder.order_code_is_valid.setVisibility(View.GONE);
			} else if ("0".equals(resultList.get(position).getFlag())) {
				viewHolder.order_state.setImageResource(R.drawable.is_valid);
				viewHolder.order_code_is_valid.setText("No." + resultList.get(position).getCode());
				viewHolder.order_code_is_valid.setVisibility(View.VISIBLE);
				if ("0".equals(resultList.get(position).getType())) {
					viewHolder.cancel_order.setVisibility(View.VISIBLE);
				} else {
					viewHolder.cancel_order.setVisibility(View.GONE);
				}
				viewHolder.order_code_isjoined.setVisibility(View.GONE);
				viewHolder.order_code_is_overtime.setVisibility(View.GONE);
			} else {

			}
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					if ("0".equals(resultList.get(position).getType())) {
						Intent intent = new Intent();
						intent.setClass(MyorderListActivity.this, GroupDetailActivity.class);
						intent.putExtra("messageId", resultList.get(position).getMessageId());
						startActivity(intent);
					}

				}
			});
			return view;
		}

		class ViewHolder {
			TextView order_title, order_content, order_code, order_code_is_overtime, order_code_isjoined,
					order_code_is_valid;
			LinearLayout myLayout;
			ImageView order_state, red_envelope;
			RelativeLayout order_ralative;
			TextView order_state_flg;
			Button cancel_order;
		}
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

	}

	/**
	 * 取消报名提示
	 *
	 * @param messageId
	 */
	@SuppressWarnings("unchecked")
	private void checkSignOut(final String messageId) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); //
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "signoutAlertNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("messageId", messageId));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mGroupJoinBean = gson.fromJson(result, GroupJoinBean.class);
				} catch (Exception e) {
					return;
				}

				if ("0".equals(mGroupJoinBean.getIsError())) {

					CustomDialog.Builder customBuilder = new CustomDialog.Builder(MyorderListActivity.this);
					ImageView img = new ImageView(MyorderListActivity.this);
					img.setImageResource(R.drawable.ic_launcher);
					customBuilder.setImgIcon(img).setMessage(mGroupJoinBean.getResultCode())

					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							signOutJsonData(messageId);
							dialog.dismiss();

						}
					}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							dialog.dismiss();

						}
					});
					customBuilder.create().show();
				} else if ("1".equals(mGroupJoinBean.getIsError())) {
					stopProgressDialog();
					CustomDialog.Builder customBuilder = new CustomDialog.Builder(MyorderListActivity.this);
					ImageView img = new ImageView(MyorderListActivity.this);
					img.setImageResource(R.drawable.ic_launcher);
					customBuilder.setImgIcon(img).setMessage(mGroupJoinBean.getResultCode())

					.setPositiveButton("确认", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {

							dialog.dismiss();

						}
					});
					customBuilder.create().show();
					stopProgressDialog();
				} else {
					stopProgressDialog();
					Alert.error(MyorderListActivity.this, mGroupJoinBean.getResultCode());
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(MyorderListActivity.this,"与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.GROUP).execute(params);
	}

	/**
	 * 退出
	 *
	 * @param messageId
	 */
	@SuppressWarnings("unchecked")
	private void signOutJsonData(String messageId) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); //
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "signoutNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("messageId", messageId));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if ("0".equals(mCloudBeansBean.getResultCode())) {

					Alert.info(MyorderListActivity.this, "退出成功");
					ConfigCacheUtil.clearCache(null);
					jsonData();
				} else {
					stopProgressDialog();
					Alert.info(MyorderListActivity.this, mCloudBeansBean.getResultCode());
				}

			}

			@Override
			public void onFail(String exception) {

				Alert.error(MyorderListActivity.this, "与服务器连接失败，请检查网络");
				stopProgressDialog();
			}
		}, GroupBean.class, AppConfig.GROUP).execute(params);
	}
}
